﻿using System;
using System.Collections.Generic;

class SquareWithMaxSum
{
    static void printMatrix(int[,] matr)
    {
        for (int i = 0; i < matr.GetLength(0); i++)
        {
            for (int j = 0; j < matr.GetLength(1); j++)
            {
                Console.Write("{0,4}",matr[i,j]);
            }
            Console.WriteLine();
        }
    }
    static void Main()
    {
        Console.WriteLine("Enter the dimentions of a rectanglular matrix NxM (N < M and N,M >=3):");
        Console.WriteLine();
        Console.WriteLine("Enter N:");
        int dimentionN = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter M:");
        int dimentionK = int.Parse(Console.ReadLine());
        int[,] Matrix = new int[dimentionN, dimentionK];
        int bestElementsSum = int.MinValue;
        Console.WriteLine("Enter the elements of the matrix row by row:");
        for (int row = 0; row < Matrix.GetLength(0); row++)
        {
            for (int col = 0; col < Matrix.GetLength(1); col++)
            {
                Console.WriteLine("Enter element [{0},{1}]",row,col);
                Matrix[row, col] = int.Parse(Console.ReadLine());
            }
        }
        Console.WriteLine();
        Console.WriteLine("The matrix you entered is:");
        printMatrix(Matrix);
        Console.WriteLine();
        int bestRow = 0;
        int bestCol = 0;
        for (int rows = 0; rows < Matrix.GetLength(0) - 2; rows++)
        {
            for (int cols = 0; cols < Matrix.GetLength(1) - 2; cols++)
            {
                int sumOfelements = Matrix[rows, cols] + Matrix[rows + 1, cols] + Matrix[rows + 2, cols] +
                    Matrix[rows, cols + 1] + Matrix[rows + 1, cols + 1] + Matrix[rows + 2, cols + 1] +
                    Matrix[rows, cols + 2] + Matrix[rows + 1, cols + 2] + Matrix[rows + 2, cols + 2];

                if (sumOfelements > bestElementsSum)
                {
                    bestElementsSum = sumOfelements;
                    bestRow = rows;
                    bestCol = cols;
                }
            }
        }
        Console.WriteLine("The square with max sum of it's elements is:");
        Console.WriteLine("{0} {1} {2}", Matrix[bestRow, bestCol], Matrix[bestRow, bestCol+1], Matrix[bestRow, bestCol + 2]);
        Console.WriteLine();
        Console.WriteLine("{0} {1} {2}", Matrix[bestRow + 1, bestCol], Matrix[bestRow + 1, bestCol + 1], Matrix[bestRow + 1, bestCol + 2]);
        Console.WriteLine();
        Console.WriteLine("{0} {1} {2}", Matrix[bestRow + 2, bestCol], Matrix[bestRow + 2, bestCol+1], Matrix[bestRow + 2, bestCol+2]);
        Console.WriteLine();
    }
}

